package com.wm.blog_web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wm.blog_common.base.BeanUtils;
import com.wm.blog_common.bean.PageHelper;
import com.wm.blog_common.bean.QueryPage;
import com.wm.blog_common.domain.TBlogSortDO;
import com.wm.blog_common.entity.TBlog;
import com.wm.blog_common.entity.TBlogSort;
import com.wm.blog_common.entity.TFile;
import com.wm.blog_common.enums.DeleteFlag;
import com.wm.blog_common.enums.PublishFlag;
import com.wm.blog_common.result.Result;
import com.wm.blog_web.controller.resp.SortResp;
import com.wm.blog_web.dao.TBlogDAO;
import com.wm.blog_web.dao.TBlogSortDAO;
import com.wm.blog_web.query.TBlogSortQuery;
import com.wm.picture_interface.feign.PictureFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客分类表 服务实现类
 * </p>
 *
 * @author 半卷流年
 * @since 2020-03-24
 */
@Service
@Slf4j
public class TBlogSortService{
    @Autowired
    private TBlogSortDAO tBlogSortDAO;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private TBlogDAO tBlogDAO;

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Result<TBlogSortDO> selectById(Long id){
        return Result.success(BeanUtils.copyProperties(tBlogSortDAO.getById(id),TBlogSortDO.class));
    }

    /**
    * 根据ID删除
    * @param id
    * @return
    */
    public Result deleteById(Long id){
        return tBlogSortDAO.removeById(id)?Result.success():Result.failure();
    }

    /**
    * 添加
    * @param tBlogSort
    * @return
    */
    public Result insert(TBlogSort tBlogSort){
        return tBlogSortDAO.save(tBlogSort)?Result.success():Result.failure();
    }

    /**
    * 修改
    * @param tBlogSort
    * @return
    */
    public Result update(TBlogSort tBlogSort){
        return tBlogSortDAO.updateById(tBlogSort)?Result.success():Result.failure();
    }

    /**
    * 统计总数
    *
    * @param query
    * @return
    */
    public Result<Integer> count(TBlogSortQuery query) {
        return Result.success(tBlogSortDAO.count(this.combineQuery(query)));
    }

    /**
    * 列表查询
    * @param query
    * @return
    */
    public Result<List<TBlogSortDO>> list(TBlogSortQuery query){
        return Result.success(BeanUtils.copyListProperties(tBlogSortDAO.list(this.combineQuery(query)),TBlogSortDO.class));
    }
    /**
    * 分页查询
    * @param page
    * @return
    */
    public Result<Page<TBlogSortDO>> page(QueryPage page, TBlogSortQuery query){
        return Result.success(PageHelper.newPage(tBlogSortDAO.page(page,this.combineQuery(query)),TBlogSortDO.class));
    }

    /**
    * 组装查询条件
    *
    * @param query
    * @return
    */
    private QueryWrapper<TBlogSort> combineQuery(TBlogSortQuery query) {
        QueryWrapper<TBlogSort> wrapper = new QueryWrapper<>();
        Optional.ofNullable(query).ifPresent(item -> {
            Optional.ofNullable(query.getStatus()).ifPresent(y -> {
                wrapper.eq("status",y);
            });
        });
        return wrapper;
    }

    /**
     * 博客类型list
     * @return
     */
    public Result sortList() {
        TBlogSortQuery sortQuery = new TBlogSortQuery();
        sortQuery.setStatus(DeleteFlag.ENABLE.getValue());
        QueryWrapper<TBlogSort> wrapper = this.combineQuery(sortQuery);
        List<TBlogSort> list = Optional
                .ofNullable(tBlogSortDAO.list(wrapper))
                .orElse(Collections.emptyList());
        List<SortResp> respList = Optional
                .ofNullable(BeanUtils.copyListProperties(list, SortResp.class))
                .orElse(Collections.emptyList());
        if(!CollectionUtils.isEmpty(list)){
            //图片idList
            List<Long> picIdList = respList
                    .stream()
                    .map(SortResp::getFileId)
                    .distinct()
                    .collect(Collectors.toList());
            CompletableFuture<Map<Long, String>> futurePic = CompletableFuture.supplyAsync(() -> {
                return Optional
                        .ofNullable(pictureFeignClient.getByIdList(picIdList).getData())
                        .orElse(Collections.emptyList())
                        .stream()
                        .collect(Collectors.toMap(TFile::getId, TFile::getPicUrl));
            }, threadPoolTaskExecutor);
            //统计分类文章的数量
            CompletableFuture<Void> futureCount = CompletableFuture.runAsync(() -> {
                respList.forEach(item -> {
                    QueryWrapper<TBlog> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("blog_sort_id", item.getId());
                    queryWrapper.eq("is_publish", PublishFlag.PUBLISH.getValue());
                    queryWrapper.eq("status",DeleteFlag.ENABLE.getValue());
                    int count = tBlogDAO.count(queryWrapper);
                    item.setArticleCount(count);
                });
            });
            try {
                Map<Long, String> map = futurePic.get();
                futureCount.get();
                respList.forEach(item -> {
                    item.setPicUrl(map.getOrDefault(item.getFileId(),null));
                });
                return Result.success(respList);
            } catch (InterruptedException | ExecutionException e) {
                log.error("线程执行异常:{}",e.getMessage(),e);
            }
        }
        return Result.success();
    }
}
